package org.sbear.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import org.sbear.handler.UserClientHandler;
import org.sbear.pojo.RpcRequest;
import org.sbear.util.JSONSerializer;
import org.sbear.util.RpcDecoder;
import org.sbear.util.RpcEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author xxyWi
 */
public class RPCConsumer {

    /**
     * 1.创建一个线程池对象  -- 它要处理我们自定义事件
     */
    private static ExecutorService executorService =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    /**
     * 2.声明一个自定义事件处理器  UserClientHandler
     */
    private static UserClientHandler userClientHandler;

    /**
     * 3.编写方法,初始化客户端  (创建连接池  bootStrap  设置bootstrap  连接服务器)
     *
     * @throws InterruptedException
     */
    public static void initClient() throws InterruptedException {

        //1) 初始化事件处理器-UserClientHandler
        userClientHandler = new UserClientHandler();
        //2)创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        //3)创建客户端的引导对象
        Bootstrap bootstrap = new Bootstrap();
        //4)配置启动引导对象
        bootstrap.group(group)
                //设置通道为NIO
                .channel(NioSocketChannel.class)
                //设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY, true)
                //监听channel 并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取ChannelPipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //设置编码
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        //pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        //添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });
        //
        bootstrap.connect("127.0.0.1", 8999).sync();

    }


    /**
     * 4.编写一个方法,使用JDK的动态代理创建对象
     * serviceClass 接口类型,根据哪个接口生成子类代理对象;   providerParam :  "UserService#sayHello#"
     *
     * @param serviceClass
     * @param className
     * @param methodName
     * @return
     */
    public Object createProxy(final Class<?> serviceClass, final String className, final String methodName) {
        //借助JDK动态代理生成代理对象
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                if (userClientHandler == null) {
                    initClient();
                }

                // 设置参数
                RpcRequest req = new RpcRequest();
                //className必须与服务端中的实现类在ioc容器内的名称完全一致，否则会找不到实现类对象
                req.setClassName(className);
                //使用灵活判断途径时，方法名和方法传参类型列表都必须完全一致
                req.setMethodName(methodName);
                Class<?>[] clazz = {String.class};
                req.setParameterTypes(clazz);
                //实际传参
                req.setParameters(args);
                //userClientHandler.setPara(providerName+args[0]);
                userClientHandler.setRpcRequest(req);
                // 去服务端请求数据
                return executorService.submit(userClientHandler).get();
            }
        });
    }
}
